package com.zmn.oms.admin.controller.work.list;

import com.google.common.collect.Lists;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.mcc.common.constant.DpermitConsts;
import com.zmn.mcc.common.dto.permit.SpermitDTO;
import com.zmn.mcc.common.dto.role.RoleDRO;
import com.zmn.mcc.dubbo.interfaces.role.RoleListRemoteService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：工单列表controller
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
public class WorkListTabBaseController extends OmsBaseController {

    @Reference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    private RoleListRemoteService roleListRemoteService;

     /**
     * 处理tab 查询
     * @param query
     */
     void processTagTypeQuery(OrderWorkQuery query){

        // 待确认、待派单、工程师未接单快捷查询
        Integer tabType = query.getTabType();
        if (tabType != null) {
            switch (tabType) {
                case OmsPageConsts.QUERY_TAB_WAIT_CONFIRM:
                    // 待确认 (已录入-进行中)
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_INPUT));
                    // 进行中
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    if (!super.isBranchCompany()) {
                        // 总部不限制 数据权限-组织架构
                        query.setPermitOrganize(GlobalConsts.NO);
                    }
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_DISTRIBUTE:
                    // 待派单 （已接单-进行中）
                    //query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_ASSIGN));
                    query.setIsWaitDistribute(true);
                    // 进行中
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_DUTY:
                    // 待预约（状态结果：未取消/未完成-进行中” & 预约时间为：空
                    query.setExistDutyTime(GlobalConsts.NO);
                    query.setExistCompleteTime(GlobalConsts.NO);
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_TAKE:
                    // 待领单 （已派单-进行中）
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_DISTRIBUTE));
                    // 进行中
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_ACCOUNT:
                    // 待算账查询
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_CHECKOUT));
                    break;
                case OmsPageConsts.QUERY_TAB_REIMBURSE:
                    // 待报销查询
                    query.setPartReimburseStatus(OrderConsts.PART_REIMBURSE_STATUS_DOING);
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_CHECKOUT, OrderStatusConsts.WORK_STATUS_ACCOUNT));
                    break;
                case OmsPageConsts.QUERY_TAB_INVOICE:
                    // 本月开发票
                    Date now = DateUtil.getNow();
                    String firstDay = DateUtil.getMonthFirstDay(now);
                    String lastDay = DateUtil.getMonthLastDay(now);
                    query.setInvoiceTime(firstDay + "," + lastDay);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_VISIT:
                    // 待回访查询
                    query.setReplyVisited(GlobalConsts.NO);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_CHECKOUT:
                    // 待收单查询 （工单完成 & （金额无需审核 || 金额审核成功））
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_COMPLETE));
                    query.setAmountReviewStatus(Lists.newArrayList(OrderConsts.REVIEW_STATUS_SUCCESS, GlobalConsts.NONE));
                    // 进行中
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_TURN:
                    // 待转单
                    // 工单状态：已确认-进行中
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_CONFIRM));
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    if (!super.isBranchCompany()) {
                        // 总部不限制 数据权限-组织架构
                        query.setPermitOrganize(GlobalConsts.NO);
                    }
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_ASSIGN:
                    // 待分单
                    // 工单状态：已确认-进行中
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_CONFIRM));
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    query.setInScopeService(GlobalConsts.YES);

                    if (!super.isBranchCompany()) {
                        // 总部不限制 数据权限-组织架构
                        query.setPermitOrganize(GlobalConsts.NO);
                    }
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_REFUND:
                    // 待退款
                    query.setRefundReviewStatus(OrderConsts.REVIEW_STATUS_DOING);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_SERVICE_COMPLETE_REVIEW:
                    // 待服务审核
                    query.setServiceCompleteReviewStatus(OrderConsts.REVIEW_STATUS_DOING);
                    break;
                case OmsPageConsts.QUERY_TAB_CANCEL:
                    // 取消缘由（弃单/失败）
                    query.setWorkResultStatusList(Lists.newArrayList(OrderStatusConsts.WORK_RESULT_FAIL, OrderStatusConsts.WORK_RESULT_DISCARD));
                    query.setExistCompleteTime(GlobalConsts.NO);
                    break;
                case OmsPageConsts.QUERY_TAB_TMAIL:
                    // 天猫订单
                    if (CollectionUtils.isEmpty(query.getChannelIdList())) {
                        query.setChannelIdList(DefaultChannelListConsts.getInstance().getTmailChannelIdList());
                    }
                    break;
                case OmsPageConsts.QUERY_TAB_QUOTATION:
                    // 计价器工单
                    query.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_FAULT);
                    query.setWorkType(Lists.newArrayList(OrderConsts.ORDER_TYPE_NEW));
                    query.setExistCheckoutTime(GlobalConsts.YES);
                    if (Objects.equals(query.getIsQuotationValid(), GlobalConsts.NONE)) {
                        query.setIsQuotationValid(null);
                        query.setExistQuotationValid(GlobalConsts.NO);
                    }
                    break;
                case OmsPageConsts.QUERY_TAB_QUOTATION_THREE:
                    // 计价器工单
                    query.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
                    query.setFinalPrice(GlobalConsts.NO);
                    query.setWorkType(Lists.newArrayList(OrderConsts.ORDER_TYPE_NEW));
                    query.setExistCheckoutTime(GlobalConsts.YES);
                    if (Objects.equals(query.getIsQuotationValid(), GlobalConsts.YES)) {
                        query.setTagId(OrderTagConsts.TAG_ID_WORK_QUOTATION_THREE_VALID);
                    } else if (Objects.equals(query.getIsQuotationValid(), GlobalConsts.NO)) {
                        query.setNonTagId(OrderTagConsts.TAG_ID_WORK_QUOTATION_THREE_VALID);
                    }
                    query.setIsQuotationValid(null);
                    break;
                default:
                    // 不处理
                    break;
            }
        }
    }

    /**
     * 根据权限处理导出数量
     *
     * @param query
     */
    protected void processExportPermitQuery(OrderWorkQuery query) {
        ResponseDTO<List<RoleDRO>> listResponseDTO = roleListRemoteService.listByIds(super.getCurrentStaff().getRoleIds());
        List<RoleDRO> roleDROList = listResponseDTO.getData();
        if (CollectionUtils.isEmpty(roleDROList)) {
            return;
        }

        RoleDRO roleDRO = roleDROList.stream().max((item1, item2) -> {
            if (Objects.isNull(item1.getExportLimit())) {
                return -1;
            }
            if (Objects.isNull(item2.getExportLimit())) {
                return 1;
            }
            if (item1.getExportLimit() > item2.getExportLimit()) {
                return 1;
            } else {
                return -1;
            }
        }).get();

        if (Objects.isNull(roleDRO.getExportLimit())) {
            return;
        }

        if ((roleDRO.getExportLimit() <= 0)) {
            query.setNoneQuery(GlobalConsts.YES);
        } else {
            query.setPageSize(roleDRO.getExportLimit());
        }
    }

    protected void setDefaultModelAndView(ModelAndView mv) {
        SpermitDTO<Integer> orgSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(getCurrentStaff().getStaffId(), DpermitConsts.TYPE_ORGANIZE_SUB, true);
        mv.addObject("dpermitOrgIdList", orgSpermitDTO.getItems());

        List<Integer> deptSpermitList = Lists.newArrayList();
        SpermitDTO<Integer> deptSpermitDTO0 = staffPermitRemoteService.listDpermitByStaffId(getCurrentStaff().getStaffId(), DpermitConsts.TYPE_DEPT, true);
        if (CollectionUtils.isNotEmpty(deptSpermitDTO0.getItems())) {
            deptSpermitList.addAll(deptSpermitDTO0.getItems());
        }
        SpermitDTO<Integer> deptSpermitDTO1 = staffPermitRemoteService.listDpermitByStaffId(getCurrentStaff().getStaffId(), DpermitConsts.TYPE_DEPT_L1, true);
        if (CollectionUtils.isNotEmpty(deptSpermitDTO1.getItems())) {
            deptSpermitList.addAll(deptSpermitDTO1.getItems());
        }
        SpermitDTO<Integer> deptSpermitDTO2 = staffPermitRemoteService.listDpermitByStaffId(getCurrentStaff().getStaffId(), DpermitConsts.TYPE_DEPT_L2, true);
        if (CollectionUtils.isNotEmpty(deptSpermitDTO2.getItems())) {
            deptSpermitList.addAll(deptSpermitDTO2.getItems());
        }
        SpermitDTO<Integer> deptSpermitDTO3 = staffPermitRemoteService.listDpermitByStaffId(getCurrentStaff().getStaffId(), DpermitConsts.TYPE_DEPT_L3, true);
        if (CollectionUtils.isNotEmpty(deptSpermitDTO3.getItems())) {
            deptSpermitList.addAll(deptSpermitDTO3.getItems());
        }
        mv.addObject("dpermitDeptIdList", deptSpermitList);
    }

    /**
     * 设置回溯时间
     *
     * @param mv
     */
    protected void setDayLimit(ModelAndView mv) {
        ResponseDTO<List<RoleDRO>> listResponseDTO = roleListRemoteService.listByIds(super.getCurrentStaff().getRoleIds());
        List<RoleDRO> roleDROList = listResponseDTO.getData();
        if (CollectionUtils.isEmpty(roleDROList)) {
            mv.addObject("minTime", "");
            return;
        }
        RoleDRO roleDRO = roleDROList.stream().max((item1, item2) -> {
            if (Objects.isNull(item1.getDayLimit())) {
                return -1;
            }
            if (Objects.isNull(item2.getDayLimit())) {
                return 1;
            }
            if (item1.getDayLimit() > item2.getDayLimit()) {
                return 1;
            } else {
                return -1;
            }
        }).get();

        if (Objects.nonNull(roleDRO.getDayLimit())) {
            Date minDate = DateUtil.addDays(DateUtil.getNow(), -1 * roleDRO.getDayLimit());
            mv.addObject("minTime", DateUtil.toString(minDate, "yyyy-MM-dd 00:00:00"));
        } else {
            mv.addObject("minTime", "");
        }
    }
}